package com.chuji.crmcj.act;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.ConnAdapter;
import com.chuji.crmcj.adapter.PotentialAdapter;
import com.chuji.crmcj.adapter.SecHisAdp;
import com.chuji.crmcj.bean.ConnCusInfo;
import com.chuji.crmcj.bean.SearchPotenInfo;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by w.pitt on 2016/1/12.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private RelativeLayout mSearchBar;
    private ImageView mIv_back;
    private ImageView mBt_search;
    private EditText mEt_search;
    private SecHisAdp historyAdapter;
    //    private String salerID;
    /*搜索历史*/
    private ListView mLvHistory;
    private String flowID;
    /*搜索链接*/
    private PullToRefreshListView mLvConCus;
    private TextView mClearHis;
    private LinearLayout mLlSecHis;
    private int length;
    private String[] splits;
    /*搜索的数据*/
    private String mSecData;
    private int lable;
    private ConnAdapter adapter;
    private String userID;
    private PotentialAdapter potentialAdapter;
    private String[] newArrays;
    private String[] history_arr = new String[]{};
    private TextView mTv_search_title;
    private LinearLayout mLl_have_data;
    private View ll_left1;
    private SearchPotenInfo potentialInfo;
    private List<ConnCusInfo.ApiParamObjEntity> apiParamObj;
    private ConnCusInfo connCusInfo;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_search);
        mSearchBar = (RelativeLayout) findViewById(R.id.searchBar);
        mLlSecHis = (LinearLayout) findViewById(R.id.ll_show_history);
        mTv_search_title = (TextView) findViewById(R.id.tv_search_title);
        mLl_have_data = (LinearLayout) findViewById(R.id.ll_have_data);
        mIv_back = (ImageView) findViewById(R.id.iv_back);
        mBt_search = (ImageView) findViewById(R.id.bt_search);
        mEt_search = (EditText) findViewById(R.id.et_search);
        mLvHistory = (ListView) findViewById(R.id.lv_history);
        mLvConCus = (PullToRefreshListView) findViewById(R.id.lv_search_data);
        mClearHis = (TextView) findViewById(R.id.tv_clear_history);
        ll_left1 = findViewById(R.id.ll_left1);

        //只支持下拉加载
        mLvConCus.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mLvConCus.getRefreshableView().setDivider(null);
        mLvConCus.getRefreshableView().setSelector(android.R.color.transparent);
    }

    /*历史记录*/
    public List<String> mHisData = new ArrayList<String>();

    @Override
    protected void initData() {
//        salerID = SPUtils.getString(UIUtils.getContext(), "SalerID", "");
        flowID = SPUtils.getString(UIUtils.getContext(), "FlowID", "");
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        Intent intent = getIntent();
        lable = intent.getIntExtra("Lable", -1);

        /*关联初始化  不显示历史记录*/
        if (lable == ConstantValue.SEARCHSELF || lable == ConstantValue.SEARCHOTHER) {
            mLlSecHis.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        showHistoryData();
        mLvConCus.getRefreshableView().setSelection(0);
    }

    private void showHistoryData() {
        String searchHis = SPUtils.getString(UIUtils.getContext(), "SearchHis", "");
        if (searchHis.length() == 0) {
        } else {
            // 用逗号分割内容返回数组
            history_arr = searchHis.split(",");
        }
        //保留10条数据
        if (history_arr.length > 10) {
            String[] newArrays = new String[10];
            //实现数组之间的复制
            System.arraycopy(history_arr, 0, newArrays, 0, 10);
            mHisData = Arrays.asList(newArrays);
            setAdapter(newArrays);
        } else {
            mHisData = Arrays.asList(history_arr);
            setAdapter(history_arr);
        }
    }

    private void setAdapter(String[] mArrays) {
        if (historyAdapter == null) {
            historyAdapter = new SecHisAdp(mArrays);
            mLvHistory.setAdapter(historyAdapter);
        } else {
            historyAdapter.notifyDataSetChanged();
        }
    }

    private boolean isRequest = false;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            /*隐藏软键盘*/
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(), 0);
            }
            String apiKey = "";
            if (lable == ConstantValue.SEARCHSELF) {
                //查询自己
                apiKey = UrlUtils.GetMySelfPassengerList;
                searchData(apiKey, 1);
            } else if (lable == ConstantValue.SEARCHOTHER) {
                //查询别人
                apiKey = UrlUtils.GetOtherPassengerList;
                searchData(apiKey, 1);
            } else {
//                if (!isRequest) {
                mSecData = mEt_search.getText().toString().trim();
                reques(mSecData);
//                isRequest = true;
//                }
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 关联
     * 查询  自己  or  他人
     *
     * @param apiKey
     */
    private void searchData(String apiKey, int pageIndex) {
        String str = mEt_search.getText().toString().trim();
        String strURL = String.format(apiKey + "&SalesID=%s&Str=%s&PageSize=10&PageIndex=%s", userID, str, pageIndex);
        volleyRequest(strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        connCusInfo = JSON.parseObject(s, ConnCusInfo.class);
                        UIUtils.runInMainThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (connCusInfo.getApiParamObj().size() == 0) {
                                                            mLl_have_data.setVisibility(View.GONE);
                                                        } else {
                                                            if (adapter == null) {
                                                                mLl_have_data.setVisibility(View.VISIBLE);
                                                                apiParamObj = connCusInfo.getApiParamObj();
                                                                adapter = new ConnAdapter(SearchActivity.this, apiParamObj, userID, flowID);
                                                                mLvConCus.setAdapter(adapter);
                                                            } else {
                                                                //在这判断 下拉书刷新  还是上啦加载
                                                                apiParamObj = adapter.getList();
                                                                //分页加载
                                                                if (connCusInfo.getApiParamObj().size() == 0) {
                                                                    UIUtils.showToastSafe("已经到达底部");
                                                                } else {
                                                                    //滚动加载数据
                                                                    apiParamObj.addAll(connCusInfo.getApiParamObj());
                                                                    adapter.notifyDataSetChanged();
                                                                }
                                                            }
                                                        }
                                                        isRefreshing = false;
                                                        mLvConCus.onRefreshComplete();
                                                    }
                                                }
                        );
                    }
                }

        );
    }

    @Override
    protected void initListener() {
        mBt_search.setOnClickListener(this);
        ll_left1.setOnClickListener(this);
        mClearHis.setOnClickListener(this);
        mLvHistory.setOnItemClickListener(this);

        mLvConCus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SearchActivity.this, ClientDetailAct.class);
                String customerID = searchList.get(position - 1).getCustomerID();
                intent.putExtra("CustomerID", customerID);
                startActivity(intent);
            }
        });

        mLvConCus.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                String str = DateUtils.formatDateTime(SearchActivity.this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                mLvConCus.getLoadingLayoutProxy().setRefreshingLabel("正在加载");
                mLvConCus.getLoadingLayoutProxy().setPullLabel("上拉加载更多");
                mLvConCus.getLoadingLayoutProxy().setReleaseLabel("释放开始加载");
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel("最后加载时间:" + str);

                UIUtils.showToastSafe("上拉加载");
                if (!isRefreshing) {
                    isRefreshing = true;
                    getBoutiqueNetData();
                } else {
                    mLvConCus.onRefreshComplete();
                }
            }
        });
    }

    private List<SearchPotenInfo.ApiParamObjEntity> searchList;

    private int initIndex = 1;

    //上拉加载专用
    private void getBoutiqueNetData() {
        //第一次
        if (searchList == null) {
            searchList = new ArrayList<SearchPotenInfo.ApiParamObjEntity>();
            initIndex = 1;
        } else {
            initIndex++;
        }
        String apiKey;
        if (lable == ConstantValue.SEARCHSELF) {
            apiKey = UrlUtils.GetMySelfPassengerList;
            searchData(apiKey, initIndex);
        } else if (lable == ConstantValue.SEARCHOTHER) {
            //查询别人
            apiKey = UrlUtils.GetOtherPassengerList;
            searchData(apiKey, initIndex);
        } else {
            mSecData = mEt_search.getText().toString().trim();
            requestSearch(mSecData, initIndex);
        }
    }

    private boolean isRefreshing;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_search:
                mSecData = mEt_search.getText().toString().trim();
                reques(mSecData);
                break;
            case R.id.ll_left1:
                finish();
                break;
            case R.id.tv_clear_history:
                clearHistory();
                break;
        }
    }

    private void clearHistory() {
        mLlSecHis.setVisibility(View.GONE);
        SPUtils.saveString(UIUtils.getContext(), "SearchHis", "");
        UIUtils.showToastSafe("记录删除成功");
    }

    private void reques(String mSecData) {
        if (TextUtils.isEmpty(mSecData)) {
            UIUtils.showToastSafe("请输入搜索内容");
        } else {
            String old_his = SPUtils.getString(UIUtils.getContext(), "SearchHis", "");
            //利用StringBuild.append新增内容，逗号便于读取内容拆分
            StringBuilder builder = new StringBuilder(old_his);
            StringBuilder newBuilder = new StringBuilder();

            String[] items = old_his.split(",");
            // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加 将该记录转移到头部
            if (old_his.contains(mSecData + ",")) {
                for (int i = 0; i < items.length; i++) {
                    if ((!items[i].equals(mSecData)) && items[i] != "" && items[i] != null) {
                        newBuilder.append(items[i] + ",");
                    }
                }
                builder = newBuilder;
            }
            builder.insert(0, mSecData + ",");
            SPUtils.saveString(UIUtils.getContext(), "SearchHis", builder.toString());
            requestSearch(mSecData, 1);
        }
    }

    private void requestSearch(String mSecData, int pageIndex) {
        String strURL = String.format(UrlUtils.GETSAlESPASLIST + "&SalesID=%s&Str=%s&PageSize=10&PageIndex=%d", userID, mSecData, pageIndex);
        volleyRequest(strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        potentialInfo = JSON.parseObject(s, SearchPotenInfo.class);
                        UIUtils.runInMainThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (potentialInfo.getApiParamObj().size() == 0) {
                                                            UIUtils.showToastSafe("未搜索到数据");
                                                            mLlSecHis.setVisibility(View.GONE);
                                                        } else {
                                                            //搜索记录消失
                                                            mLlSecHis.setVisibility(View.GONE);
                                                            mLl_have_data.setVisibility(View.VISIBLE);
                                                            if (potentialAdapter == null) {
                                                                searchList = potentialInfo.getApiParamObj();
                                                                potentialAdapter = new PotentialAdapter(UIUtils.getContext(), searchList);
                                                                mLvConCus.setAdapter(potentialAdapter);
                                                            } else {
                                                                //在这判断 下拉刷新  还是上啦加载
                                                                searchList = potentialAdapter.getList();
                                                                if (searchList.isEmpty()) {
                                                                    return;
                                                                }
                                                                //分页加载
                                                                if (potentialInfo.getApiParamObj().size() == 0) {
                                                                    UIUtils.showToastSafe("已经到达底部");
                                                                } else {
                                                                    //滚动加载数据
                                                                    searchList.addAll(potentialInfo.getApiParamObj());
                                                                    potentialAdapter.notifyDataSetChanged();
                                                                }
                                                            }
                                                        }
                                                        isRefreshing = false;
                                                        mLvConCus.onRefreshComplete();
                                                    }
                                                }
                        );
                    }
                }

        );
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        reques(mHisData.get(position));
    }
}
